﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using DunSilverlight.Web.Comm;
using DunLibrary.User;
using System.ServiceModel.Activation;
using NHibernate;
using DunSilverlight.Web.Serializable;
using NHibernate.Engine;
using System.Data;

namespace DunSilverlight.Web.UserWcf
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“RoleService”。
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class RoleService : BaseService<Role>, IRoleService
    {

        public string GetRights(int RoleId)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                try
                {
                    Role role = sess.CreateQuery("from Role where Id=:Id").SetParameter<int>("Id", RoleId).UniqueResult<Role>();


                    if (role != null)
                    {
                        NHibernateUtil.Initialize(role.Rights);
                        string json = JsonSerializerHelper.EntityToJson(role.Rights);
                        return PackJsonResult("true", json, string.Empty);
                    }
                    else
                    {
                        return this.PackJsonResult("false", string.Empty, "该角色不存在");
                    }
                }
                catch (Exception ex)
                {
                    return this.PackJsonResult("false", string.Empty, ex.Message);
                }

            }
        }


        public void AddRights(int RoleId, string Rights)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                ITransaction tx = sess.BeginTransaction();

                sess.CreateSQLQuery("delete from User_Role_Right where roleId = " + RoleId + "").UniqueResult(); ;

                if (!string.IsNullOrEmpty(Rights))
                {
                    foreach (var rightId in Rights.Split(','))
                    {
                        sess.CreateSQLQuery(string.Format("insert into User_Role_Right(RoleId,RightId) values({0},{1})", RoleId, rightId)).UniqueResult();
                    }
                }
                sess.Flush();
                tx.Commit();
            }


        }


        public bool CanDelete(int RoleId)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                //int userCount = sess.CreateSQLQuery("select canDel = (select COUNT(*) from User_Role_Right where RoleId = "+RoleId+")+(select count(*) from User_User where RoleId = "+RoleId+")").UniqueResult<int>();
                int userCount = sess.CreateSQLQuery("select canDel = (select count(*) from User_User where RoleId = " + RoleId + ")").UniqueResult<int>();
                return userCount == 0;
            }
        }

        /// <summary>
        /// 因为要删除关系，所以需要重写
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public override string DeleteById(int id)
        {
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                ITransaction tx = sess.BeginTransaction();
                try
                {
                    Role entity = sess.Load<Role>(id);
                    sess.Delete(entity);
                    sess.CreateSQLQuery("delete from User_Role_Right where RoleId = " + id + "").UniqueResult();
                    sess.Flush();
                    tx.Commit();
                    return PackJsonResult("true", "true", string.Empty);
                }
                catch (Exception ex)
                {
                    tx.Rollback();
                    return PackJsonResult("false", "false", ex.Message);
                }
            }
        }


        public virtual string GetRoles()
        {
            string hql = "from Role where Name != '超级管理员'";
            using (ISession sess = HbmSessionFactory.OpenSession())
            {
                try
                {
                    IList<Role> ls = sess.CreateQuery(hql).List<Role>();

                    if (ls.Count > 0 && ls[0] == null)
                        ls.RemoveAt(0);


                    string json = JsonSerializerHelper.EntityToJson(ls);

                    string s = PackJsonListResult("true", json, string.Empty, ls.Count);

                    return s;
                }
                catch (Exception ex)
                {
                    return PackJsonListResult("false", "[]", ex.Message, 0);
                }
            }
        }
    }
}
